// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const voiceCollection = db.collection('voice')
const userCollection = db.collection('user')
const likeCollection = db.collection('liker_liked')
const cmtCollection = db.collection('comment')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  let voiceList = []
  const page = event.page || 1
  const pageSize = event.pageSize || 10
  const currentPage = (page - 1) * pageSize
  const openId = event.openId || null
  const wxContext = cloud.getWXContext()
  await voiceCollection.skip(currentPage).limit(pageSize).where(openId ? {
    _openid: openId
  } : {}).orderBy('submitDate', 'desc').get().then(res => {
    voiceList = res.data
  })

  if (openId) return voiceList //获取自己的voice时不需要评论信息

  for (let item of voiceList){
    await userCollection.where({
      _openid: item._openid
    }).get().then(res => {
      item.userInfo = res.data[0]
    })

    await likeCollection.where({
      likerOpenId: wxContext.OPENID,
      likedVoiceId: item._id
    }).count().then(count => {
      if(count.total == 0){
        item.isLike == false
      }else{
        item.isLike = true
      }
    })
    if (item._openid != wxContext.OPENID){
      await cmtCollection.where({
        voiceId: item._id,
        commentatorId: wxContext.OPENID
      }).get().then(res => {
        item.commentInfo = res.data[0]
      })
    }else{
      await cmtCollection.where({
        voiceId: item._id,
        commentatorId: _.neq(wxContext.OPENID)
      }).orderBy('commentDate', 'desc').get().then(res => {
        item.commentInfo = res.data[0]
      })
    }

    if (item.commentInfo){
      await userCollection.where({
        _openid: item.commentInfo.commentatorId
      }).get().then(res => {
        item.commentInfo.commnetatorInfo = res.data[0]
      }) 
    }
  }


  return voiceList
}